package com.ambimmort.shj.action.policybank;

/**
 * Created by Administrator on 2015/7/30.
 */

import cn.net.greenet.common.policy_service.PolicySupport;
import com.ambimmort.prserver.repository.webservice.InstanceBean;
import com.ambimmort.shj.service.policybank.PolicybankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;

@Controller("/action/policy/create_strategy_instance.do")
public class Create {
    @Autowired
    private PolicybankService policybankService;


    /**
     *
     * @param request 接收
     * @param response 响应
     * @param type 创建策略仓库类型名称
     * @param instance 创建策略仓库实例名称
     * @return
     * @throws IOException
     */
    @RequestMapping("/action/policy/create_strategy_instance.do")
    @ResponseBody
    public String action_PolicybankCreate(HttpServletRequest request, HttpServletResponse response, @RequestParam("type") String type, @RequestParam("instance") String instance) throws IOException {

        System.out.println("|||||"+type+"||___"+instance);
        //创建一个指定类型的策略仓库实例
        String username = null;
        try {
            HttpSession hsession = request.getSession(false);
            username = hsession.getAttribute("name").toString();

        } catch (Exception e) {
            response.sendRedirect("/WebManage/404.html");
        }

        ArrayList<InstanceBean> instanceList = (ArrayList<InstanceBean>) PolicySupport.getInstance().getApi().listRepositories(type);
        Set<String> instancename = new TreeSet<String>();
        for (InstanceBean i : instanceList) {
            instancename.add(i.getInstance());
        }
        if (instancename.contains(instance.trim())) {
            System.out.println("策略类型：" + type + "策略仓库：" + instance + "重复，添加失败");
           return "{\"result\":\"false\"}";

        }else{

            try {
                System.out.println("创建调用___________");
                policybankService.createDomain( type, instance);
                return  "{\"result\":\"true\"}";
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                return "{\"result\":\"false\"}";

            }
        }

    }
}
